package com.dennytech.tac.utils;

import java.util.HashMap;
import java.util.Map;

import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.URLSpan;

public class CFSpannableString {

	// {showStr, uri}
	String source;
	SpannableString result;
	Map<String, int[]> spanMap = new HashMap<String, int[]>();

	public CFSpannableString(String s) {
		source = s;

		String str = filter();
		result = setSpans(str);
	}

	public SpannableString string() {
		return result;
	}

	private SpannableString setSpans(String s) {
		SpannableString ss = new SpannableString(s);
		for (String key : spanMap.keySet()) {
			int[] pos = spanMap.get(key);
			ss.setSpan(new URLSpan(key), pos[0], pos[1],
					Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
		return ss;
	}

	private String filter() {
		StringBuilder sb = new StringBuilder();
		char[] full = source.toCharArray();

		boolean inSpan = false;
		int spanStart = 0;
		int spanEnd;
		for (int i = 0; i < full.length; i++) {
			if (full[i] == '#') {
				inSpan = true;
				spanStart = i;
				continue;
			} else if (full[i] == '&') {
				inSpan = false;
				spanEnd = i;

				try {
					String span = source.substring(spanStart + 1, spanEnd);
					if (span.length() > 0) {
						String[] spanItems = span.split(",");
						if (spanItems.length == 2) {
							int[] pos = { sb.length(),
									sb.length() + spanItems[0].length() };
							sb.append(spanItems[0]);

							spanMap.put(spanItems[1], pos);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				continue;
			} else {
				if (inSpan) {
					continue;
				} else {
					sb.append(full[i]);
				}
			}
		}
		return sb.toString();
	}

}
